package com.x2.base.serializer;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.ToStringSerializer;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;

/**
 * Title: {@link BigDecimalJsonSerializer}
 * Description: Long 类型字段序列化时转为字符串，避免js丢失精度
 */
public class BigDecimalJsonSerializer implements ObjectSerializer {
    public static final ToStringSerializer instance = new ToStringSerializer();

    public BigDecimalJsonSerializer() {
    }

    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        if (object == null) {
            out.writeNull();
        } else {
            String strVal = object.toString();
            try {
                BigDecimal bg = BigDecimal.valueOf(Double.valueOf(strVal));
                out.writeString(bg.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                out.writeString(strVal);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                out.writeNull();
            }

        }
    }
}
